package com.strp.mptcp.websocket;

import com.strp.mptcp.common.NetworkStats;
import org.springframework.stereotype.Component;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author 曹行阳
 * @version 0.1
 * @date 2025/6/12 11:34
 */
@Component
public class WebSocketManager {
    private final Map<String, WebSocketSession> sessions = new ConcurrentHashMap<>();
    private final ObjectMapper objectMapper = new ObjectMapper();

    public void addSession(WebSocketSession session) {
        sessions.put(session.getId(), session);
    }

    public void removeSession(WebSocketSession session) {
        sessions.remove(session.getId());
    }

    // 由统计模块定时调用
    public void broadcastStats(NetworkStats stats) {
        try {
            String jsonStats = objectMapper.writeValueAsString(stats);
            TextMessage message = new TextMessage(jsonStats);
            for (WebSocketSession session : sessions.values()) {
                if (session.isOpen()) {
                    session.sendMessage(message);
                }
            }
        } catch (Exception e) {
            // Log error
        }
    }
}
